//- Copyright (C) 2018-2022 Chatopera Inc, <https://www.chatopera.com>
//- 
//- Licensed under the Apache License, Version 2.0 (the "License");
//- you may not use this file except in compliance with the License.
//- You may obtain a copy of the License at
//- 
//-  http://www.apache.org/licenses/LICENSE-2.0
//- 
//-  Unless required by applicable law or agreed to in writing, software
//- distributed under the License is distributed on an "AS IS" BASIS,
//-  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//- See the License for the specific language governing permissions and
//- limitations under the License.
doctype html
// constants
- var dialog_headimg = inviteData.consult_dialog_headimg ? '/res/image.html?id=' + inviteData.consult_dialog_headimg : '/images/agent.png'
html
    head
        meta(charset='utf-8')
        meta(http-equiv='X-UA-Compatible', content='IE=edge')
        meta(http-equiv='Cache-Control', content='no-siteapp')
        meta(name='viewport', content='width=device-width,maximum-scale=1,initial-scale=1,initial-scale=1,user-scalable=no')
        meta(name='apple-mobile-web-app-capable', content='yes')
        title 在线咨询
        link(rel='shortcut icon', type='image/x-icon', href='/images/favicon.ico?t=1489039620156')
        link(rel='stylesheet', type='text/css', href='/im/css/ukefu.css')
        link#skin(rel='stylesheet', type='text/css', href='/im/css/default/ukefu.css')
        //  kindeditor
        link(rel='stylesheet', type='text/css', href='/im/js/kindeditor/themes/default/default.css')
        script(src='/js/jquery-1.10.2.min.js')
        script(type='text/javascript', src='/im/js/kindeditor/kindeditor.js')
        script(type='text/javascript', src='/im/js/kindeditor/lang/zh-CN.js')
        script(src='/im/js/socket.io.js')
        script(src='/im/js/dayjs.min.js')
        script(type='text/javascript').
            var editor, words;
            var newmessage = [], ring = [];
            newmessage['mp3'] = '/images/message.mp3';
            ring['mp3'] = '/images/ring.mp3';
            KindEditor.ready(function (K) {
                editor = K.create('textarea[name="content"]', {
                    autoHeightMode: false,
                    width: "100%",
                    resizeType: 0,
                    themeType: 'simple',
                    fontsize: 16,
                    newlineTag: "br",
                    uploadJson: "/im/image/upload.html?userid=#{userid}",
                    allowFileManager: false,
                    allowInsertUpload: false,		//增加的参数，上传图片后是否插入到当前区域
                    allowImageRemote: false,
                    filterMode: true,

                    items: ['emoticons', 'cut'],
                    htmlTags: {
                        img: ['src', 'width', 'height', 'border', 'alt', 'title', 'align', '.width', '.height', '.border'],
                        br: []
                    },
                    afterChange: function () {
                        var count = this.count()

                        var limitNum = #{ inviteData.maxwordsnum > 0 ? inviteData.maxwordsnum : 300};  //设定限制字数
                        var strValue = this.html();
                        if (count > limitNum) {
                            // 超过字数限制自动截取
                            strValue = strValue.substring(0, limitNum);
                            editor.html(strValue);
                            document.getElementById('sent').innerHTML = "发送（" + limitNum + "/" + limitNum + "）"; //输入显示
                        } else {
                            // 计算剩余字数
                            var result = limitNum - this.count();
                            if (result < 20) {
                                document.getElementById('sent').style.color = "red";
                            } else {
                                document.getElementById('sent').style.color = "#fff";
                            }
                            document.getElementById('sent').innerHTML = "发送（" + count + "/" + limitNum + "）"; //输入显示
                        }
                        if (this.count("text") == 0) {
                            strValue = "";
                        }
                        // ignore writting in Chatbot Service
                        // if(words != this.count("text")){
                        //     socket.emit('message', {
                        //         appid : "${appid!''}",
                        //         userid:"${userid!''}",
                        //         type:"writing",
                        //         session:"${sessionid!''}",
                        //         orgi:"${orgi!''}",
                        //         message : strValue
                        //     });
                        // }
                        words = this.count("text");


                    },
                    afterCreate: function () { //设置编辑器创建后执行的回调函数
                        var self = this;
                        if (#{inviteData.ctrlenter == true}) {
                            //Ctrl+Enter提交表单
                            K.ctrl(document, 13, function () {
                                self.sync();
                                sendMessage();
                            });
                            K.ctrl(self.edit.doc, 13, function () {
                                self.sync();
                                sendMessage();
                            });
                        } else {
                            // Ctrl+Enter 提交表单
                            K.ctrl(document, 13, function () {
                                self.sync();
                                sendMessage();
                            });
                            K.ctrl(self.edit.doc, 13, function () {
                                self.sync();
                                sendMessage();
                            });
                        }
                    }
                });
            });

            KindEditor.options.cssData = "body { font-size: 15px; font-family:'Microsoft Yahei', 'Helvetica', 'Simsun', 'Arial';}";
            var R3Ajax = {
                ajax: function (opt) {
                    var xhr = this.createXhrObject();
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState != 4) return;
                        (xhr.status === 200 ?
                            opt.success(xhr.responseText, xhr.responseXML) :
                            opt.error(xhr.responseText, xhr.status));
                    }
                    xhr.open(opt.type, opt.url, true);
                    if (opt.type !== 'post')
                        opt.data = null;
                    else
                        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    opt.data = this.parseQuery(opt.data);
                    xhr.send(opt.data);
                },
                post: function (url, success, data) {
                    var popt = {
                        url: url,
                        type: 'post',
                        data: data,
                        success: success,
                        error: function (data) {
                        }
                    }
                    this.ajax(popt);
                },
                get: function (url, success) {
                    var gopt = {
                        url: url,
                        type: 'get',
                        success: success,
                        error: function () {
                        }
                    }
                    this.ajax(gopt);
                },
                createXhrObject: function () {
                    var methods = [
                        function () {
                            return new XMLHttpRequest();
                        },
                        function () {
                            return new ActiveXObject('Msxml2.XMLHTTP');
                        },
                        function () {
                            return new ActiveXObject('Microsoft.XMLHTTP');
                        }
                    ];
                    for (var i = 0; len = methods.length, i < len; i++) {
                        try {
                            methods[i]();
                        } catch (e) {
                            continue;
                        }
                        this.createXhrObject = methods[i];
                        return methods[i]();
                    }
                    throw new Error('Could not create an XHR object.');
                },
                parseQuery: function (json) {
                    if (typeof json == 'object') {
                        var str = '';
                        for (var i in json) {
                            str += "&" + i + "=" + encodeURIComponent(json[i]);
                        }
                        return str.length == 0 ? str : str.substring(1);
                    } else {
                        return json;
                    }
                },
                audioplayer: function (id, file, loop) {
                    var audioplayer = document.getElementById(id);
                    if (audioplayer != null) {
                        document.body.removeChild(audioplayer);
                    }

                    if (typeof (file) != 'undefined') {
                        if (navigator.userAgent.indexOf("MSIE") > 0) { // IE
                            var player = document.createElement('bgsound');
                            player.id = id;
                            player.src = file['mp3'];
                            player.setAttribute('autostart', 'true');
                            if (loop) {
                                player.setAttribute('loop', 'infinite');
                            }
                            document.body.appendChild(player);

                        } else { // Other FF Chome Safari Opera
                            var player = document.createElement('audio');
                            player.id = id;
                            player.setAttribute('autoplay', 'autoplay');
                            if (loop) {
                                player.setAttribute('loop', 'loop');
                            }
                            document.body.appendChild(player);

                            var mp3 = document.createElement('source');
                            mp3.src = file['mp3'];
                            mp3.type = 'audio/mpeg';
                            player.appendChild(mp3);
                        }
                    }
                }
            };
            Date.prototype.format = function (fmt) {
                var o = {
                    "M+": this.getMonth() + 1,                 //月份
                    "d+": this.getDate(),                    //日
                    "h+": this.getHours(),                   //小时
                    "m+": this.getMinutes(),                 //分
                    "s+": this.getSeconds(),                 //秒
                    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                    "S": this.getMilliseconds()             //毫秒
                };
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                }
                for (var k in o) {
                    if (new RegExp("(" + k + ")").test(fmt)) {
                        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                    }
                }
                return fmt;
            }
            var R3Helper = {
                resize: function () {
                    var height = document.body.offsetHeight;
                    document.getElementById('above').style.height = (height - 194 - 50) + "px";
                }
            }


            function submitForm(form) {
                R3Ajax.post("/im/satis.html?orgi=#{orgi}", function () {
                    document.getElementById("diaShade").style.display = "none";
                    document.getElementById("dialogWrap").style.display = "none";
                    alert("服务评价已提交，请关闭浏览器！");
                    isAgentEnds = false;
                }, "id=" + form.id.value + "&satislevel=" + document.getElementById("satislevel_input").value + "&satiscomment=" + encodeURIComponent(document.getElementById("comment_input").value));
                return false;
            }

            function output(message, clazz, scroll, msgType) {
                if (clazz == "message connect-message") {
                    var messages = document.getElementsByClassName("connect-message");
                    for (inx = 0; inx < messages.length;) {
                        document.getElementById('above').removeChild(messages[inx]);
                        inx++;
                    }
                }
                var element = $("<div class='clearfix " + clazz + "'></div>");
                element.append(message);
                $('#above').append(element);
                if (scroll == null || scroll == true) {
                    if (msgType && msgType == "image") {
                        chatScorllBottom("above")
                    } else {
                        document.getElementById("above").scrollTop = document.getElementById("above").scrollHeight
                    }
                }
            }

            function update(id, message) {
                document.getElementById(id).innerHTML = message;
            }


            function createButton(message, data) {
                var element = $('<div><p>' + message + '</p><div class="button-box"></div></div>')
                var list = element.find('.button-box');
                for (let i = 0; i < data.length; i++) {
                    var item = data[i];
                    var allowClick = true;
                    var btn = $('<div class="msg-btn" style="background-color: #e6f2ff !important;">' + item.label + '</div>');
                    var regClick = function (key) {
                        btn.click(function () {
                            if (allowClick) {
                                allowClick = false;
                                socket.emit('message', {
                                appid: "#{appid}",
                                    userid: "#{userid}",
                                    type: "message",
                                    session: "#{sessionid}",
                                    orgi: "#{orgi}",
                                    message: key
                                    });
                        }
                    });
            }
            regClick(item.text);
            list.append(btn);
            }

            return element;
            }

            function createQList(message, data) {
                var element = $('<div><p>' + message + '</p><div class="button-box"></div></div>')
                var list = element.find('.button-box');
                for (let i = 0; i < data.length; i++) {
                    var item = data[i];
                    var btn = $('<div class="msg-list">' + item.label + '</div>');
                    var regClick = function (key) {
                        btn.click(function () {
                            socket.emit('message', {
                            appid: "#{appid}",
                                userid: "#{userid}",
                                type: "message",
                                session: "#{sessionid}",
                                orgi: "#{orgi}",
                                message: key
                                });
                    });
            }
            regClick(item.text);
            list.append(btn);
            }

            return element;
            }

            function createCard(message, data) {
                let item = data[0];

                let html = '<div class="card-box" style="background-color: #fff !important;"><div class="msg-card" style="background-color: #fff !important;"><img src="' + item.thumbnail + '" style="width: 80px;height: 80px;"></div><div class="msg-card msg-crad-right" style="background-color: #fff !important;"><h3 style="background-color: #fff !important;">' + item.title + '</h3><p style="background-color: #fff !important;">' + item.summary + '</p></div></div>'

                var element = $(html);
                element.click(function () {
                    window.open(item.hyperlink);
            })

            return element;
            }

            function showExtmsg(username, createtime, message, json) {
                var expmsg = JSON.parse(json.replace(/&quot;/g,'"'));

                var type = expmsg[0].type;
                var content;
                if (type == 'button') {
                    content = createButton(message, expmsg);
                } else if (type == 'qlist') {
                content = createQList(message, expmsg);
                } else if (type == 'card') {
                content = createCard(message, expmsg);
                }

                var box = $('<div class="chat-left"> <img class="user-img" src="#{dialog_headimg}" alt=""><div class="chat-message"><label  class="user">' + username + '</label><label class="time">' + createtime + '</label> </div><div class="chatting-left"><i class="arrow"></i><div class="chat-content"></div></div>');

                box.find('.chat-content').append(content);
                output(box, 'chat-block')
            }

            function showExtmsgBody(username, createtime, message, json) {
                var expmsg = JSON.parse(json.replace(/&quot;/g,'"'));

                var type = expmsg[0].type;
                var content;
                if (type == 'button') {
                    content = createButton(message, expmsg);
                } else if (type == 'qlist') {
                    content = createQList(message, expmsg);
                } else if (type == 'card') {
                    content = createCard(message, expmsg);
                }

                var box = $('')

                var box = $('<div class="chat-left"> <img class="user-img" src="#{dialog_headimg}" alt=""><div class="chat-message"><label  class="user">' + username + '</label><label class="time">' + createtime + '</label> </div><div class="chatting-left"><i class="arrow"></i><div class="chat-content"></div></div>');

                box.find('.chat-content').append(content);
                output(box, 'chat-block')
            }

            window.onbeforeunload = function () {
            }

        //  kindeditor
        style.
            .msg-btn {
                border: #4598ee 1px solid;
                padding: 5px;
                margin: 5px;
                min-width: 125px;
                text-align: center;
                display: inline-block;
                background-color: #e6f2ff;
                cursor: default;
            }

            .msg-list {
                color: #4598ee;
                cursor:pointer;
            }

            .msg-card {
                display: inline-block;
                color: #000000;
            }

            .msg-crad-right {
                position: relative;
                left: 10px;
                width: 210px;
                height: 80px;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            .card-box {
                cursor: default;
                width: 300px;
                height: 82px;
                padding: 6px;
            }

    body.ukefu-point-text(style='overflow:hidden; background:#E8E8E8')
        .large.ukefu-im-theme(style='background: white;', class=(type == 'text' ? 'ukefu-theme-border-' + inviteData.consult_dialog_color : ''))
            #containter.clearfix
                #header(class='theme' + inviteData.consult_dialog_color)
                    - var dialog_logo=inviteData.consult_dialog_logo?'/res/image.html?id='+inviteData.consult_dialog_logo:'/images/logo.png'
                    img(src=dialog_logo, style='height:30px;padding:10px;')
                    .ukefu-func-tab
                        ul
                            if models.contains("chatbot") && inviteData.ai && aiid
                                if exchange || exchange == "true"
                                    li
                                        a(href="/im/index.html?appid=" + appid + "&orgi=" + orgi + (aiid ? "&aiid=" + aiid : "") + "&ai=false" + (client ? "&client=" + client : '') + (type ? "&type=text" : "") + (skill ? "&skill=" + skill : '') + (agent ? "&agent=" + agent : '') + (title ? "&title=" + encodeURIComponent(title) : '') + (url ? "&url=" + url : '') + (traceid ? "&traceid=" + traceid : '') + "&userid=" + userid + "&sessionid=" + sessionid + "&t=" + pugHelper.currentTimeMillis()) 人工坐席
                                li.cur
                                    a(href="javascript:void(0)") 智能客服
                            else
                                li.cur
                                    a(href="javascript:void(0)") 智能客服
                .content-left
                    .chat-above#above
                        if welcomeAd
                            .clearfix.message.welcome
                                span#welcome-message
                                    if welcomeAd.adtype == "image"
                                        a(href=welcomeAd.url, title=welcomeAd.tiptext, target="_blank")
                                            img(src=welcomeAd.imgurl, style="max-width:420px;max-height:178px;margin:0px;vertical-align: middle;")
                                    else
                                        div(style="padding:0px 5px 10px 5px;border-bottom:1px solid #dedede;")
                                            a#point_ad_text(href=welcomeAd.url, title=welcomeAd.tiptext, target="_blank")= welcomeAd.content

                        .clearfix.message.welcome
                            span#welcome-message= inviteData.dialog_message ? inviteData.dialog_message : '欢迎您来咨询！欢迎使用春松客服！如需帮助请联系 info@chatopera.com'

                        for chatMessage in pugHelper.reverse(chatMessageList.content)
                            if chatMessage.userid && userid && chatMessage.calltype && chatMessage.calltype == "呼入"
                                .clearfix.chat-block
                                    .chat-right
                                        img.user-img(src="/im/img/user.png", alt="")
                                        .chat-message
                                            label.time= pugHelper.formatDate('yyyy-MM-dd HH:mm:ss', chatMessage.createtime)
                                            label.user= chatMessage.username
                                        .chatting-right
                                            i.arrow(class="arrow" + inviteData.consult_dialog_color)
                                            .chat-content(class="theme" + inviteData.consult_dialog_color)
                                                include ../media/message
                            else
                                .clearfix.chat-block
                                    // for debugging purpose
                                    //script.
                                        // console.log("chatMessage.message", '#{chatMessage.message.replaceAll("\\r|\\n", "")}'.replace(/\r?\n|\r/g, ''))
                                        // console.log("chatMessage.username", "#{chatMessage.username}")
                                        // var expmsg = "#{chatMessage.expmsg}";
                                        // if(expmsg)  console.log("chatMessage.expmsg", JSON.parse(expmsg.replace(/&quot;/g,'"')))
                                        // // && (chatMessage.message == "{CLEAR} 混合类型消息" || chatMessage.message == "{CLEAR} 图文消息")
                                    - var createtime = pugHelper.formatDate('yyyy-MM-dd HH:mm:ss', chatMessage.createtime)
                                    if chatMessage.expmsg
                                        script.
                                            try {
                                                showExtmsgBody("#{chatMessage.username}", "#{createtime}", "#{chatMessage.message}", "#{chatMessage.expmsg}");
                                            } catch (e) {
                                                console.log("unexpected result", e)
                                            }
                                    else
                                        .chat-left
                                            img.user-img(src=dialog_headimg , alt="")
                                            .chat-message
                                                label.user
                                                    if chatMessage.chatype == 'aireply'
                                                        | #{inviteData.ainame ? inviteData.ainame : '小松'}
                                                    else
                                                        | #{chatMessage.username}
                                                label.time= createtime
                                            .chatting-left
                                                i.arrow
                                                .chat-content
                                                    include ../media/message

                    .chat-bottom#bottom
                        textarea#message(name='content', style='visibility:hidden;')
                        .btn-push.clearfix
                            #surplus(style='float:left;height:34px;line-height:34px;margin: 10px 20px 10px 5px;'): a(style="color: #C7C6C6;text-decoration: none;cursor: pointer;", href="https://www.cskefu.com", target="_blank") 春松客服提供客服软件支持
                            button.send-btn.active.special.clearfix#sent(class="theme" + inviteData.consult_dialog_color, type='button', onclick='sendMessage()') 发送

                .content-rig
                    .content-list(style='padding-top:50px;')
                        .content-head
                            p 信息提示
                        ul
                            if inviteData.dialog_name != ""
                                li
                                    p= '名称：' + inviteData.dialog_name
                            if inviteData.dialog_address != ""
                                li
                                    p= '地址：' + inviteData.dialog_address
                            if inviteData.dialog_phone != ""
                                li
                                    p= '电话：' + inviteData.dialog_phone
                            if inviteData.dialog_mail != ""
                                li
                                    p= '邮件：' + inviteData.dialog_mail
                            if inviteData.dialog_introduction != ""
                                li
                                    p(style="text-indent:25px;line-height:25px;")= inviteData.dialog_introduction

                    .content-pic(style='width:100%;height:192px;')
                        if figureAds
                            - var figureAdsNum = 0
                            for figureAd in figureAds
                                if figureAd.adtype == "image" && figureAdsNum < 5
                                    - figureAdsNum = 6
                                    a(href=figureAd.url, title=figureAd.tiptext, target="_blank")
                                        img(src=figureAd.imgurl, style="max-width:100%;max-height:190px;margin:0px;vertical-align: middle;")
                                else if figureAdsNum < 5
                                    - figureAdsNum = figureAdsNum + 1
                                    if figureAdsNum == 1
                                        div(style="padding:4px 5px 1px 7px")
                                            a#point_ad_text(href=figureAd.url, title=figureAd.tiptext, target="_blank")= figureAd.content
                                    else
                                        div(style="padding:1px 5px 1px 7px")
                                            a#point_ad_text(href=figureAd.url, title=figureAd.tiptext, target="_blank")= figureAd.content
                        else if inviteData.dialog_ad
                            img(src="/res/image.html?id=" + inviteData.dialog_ad, style="height:190px;width:100%;")

    #footer
        //- 调查问卷弹框
    if sessionConfig.satisfaction
        .diaShade#diaShade(style='display: none')
        .dialogWrap#dialogWrap(style='display: none;')
            .dialogCon
                form#commentContent(onsubmit='return submitForm(this)')
                    input#agentserviceid(type='hidden', name='id')
                    h2.diaHeader.clearfix
                        span 评价
                        hr
                    p.title 您是否对此次服务满意?
                    //- 评价
                    p(style='margin-top:20px; height: 20px')
                        span(style='float:left;') 评价：
                        span(style='position: relative;top: 0px;left: 13px;')
                            - var defaultvalue = ''
                            for comment in commentList
                                input(type="radio", ,checked=comment_index == 0, name="satislevel", value=comment.code, id="dic_" + comment.id, onclick="document.getElementById('satislevel_input').value = this.value")
                                label.radio(for="dic_" + comment.id)= comment.name
                                if defaultvalue == ""
                                    - defaultvalue = comment.code
                            input#satislevel_input(type="hidden", name="t", value=defaultvalue)

                    //- 意见
                    p(style='margin-top:20px;')
                        span(style='float:left;') 意见：
                        span(style='position: relative;top: 0px;left: 10px;')
                            input#comment_input(type='hidden', name='t')
                                for item in commentItemList
                                    div(style="margin-left:55px;margin-bottom:20px;")
                                        input(type="radio", name="comment", id="item_" + item.id, value=item.id, contentname=item.name, onclick="selectOther(this.getAttribute('contentname'),this.value)")
                                        label.radio(for="item_" + item.id, style="margin-right: 0px")= item.name
                    p
                    //- 按钮
                    p.submitBtnWrap(style='margin-top: 0px')
                        input.btn.submitBtn#submitBtn(type='submit', value='提 交')

    script.
        var service_end = false;
        R3Helper.resize();
        // 调查问卷
        var diaShade = document.getElementById('diaShade');
        var dialogWrap = document.getElementById('dialogWrap');
        function popup(para) {
            diaShade.style.display = para;
            dialogWrap.style.display = para;
        }

        function chatScorllBottom(box) {
            var imgdefereds = [];  					//定义一个操作数组
            $('#' + box + ' .ukefu-media-image').each(function () {  	//遍历所有图片，将图片
                var dfd = $.Deferred();  				//定义一个将要完成某个操作的对象
                $(this).bind('load', function () {
                    dfd.resolve();  			//图片加载完成后，表示操作成功
                });
                if (this.complete) {				//如果图片加载状态为完成，那么也标识操作成功
                    setTimeout(function () {
                        dfd.resolve();
                    }, 1000);
                }
                imgdefereds.push(dfd);  			//将所有操作对象放入数组中
            })
            $.when.apply(null, imgdefereds).done(function () {  	//注册所有操作完成后的执行方法
                document.getElementById(box).scrollTop = document.getElementById(box).scrollHeight
            });
        }

        if (#{!welcomeAd}) {
            chatScorllBottom('above');
        }
        // 参数连接
        var hostname = location.hostname;
        var protocol = window.location.protocol.replace(/:/g, '');
        var username = encodeURIComponent("#{username}");
        var socket = io(protocol + '://' + hostname + ':#{port}/im/chatbot?userid=#{userid}&orgi=#{orgi}&session=#{sessionid}&appid=#{appid}&osname=!{osname}&browser=!{browser}!{skill ? "&skill=" + skill : ""}!{username ? "&nickname='+username+'" : ""}!{agent ? "&agent=" + agent : ""}!{title ? "&title=" + title : ""}!{traceid ? "&url=" + url : ""}!{traceid ? "&traceid=" + traceid : ""}!{aiid ? "&aiid=" + aiid : ""}', {transports: ['websocket', 'polling']});

        socket.on('connect', function () {
            if ('#{contacts.name}') {
                socket.emit('new', {
                    name: "#{contacts.name}",
                    phone: "#{contacts.phone}",
                    email: "#{contacts.email}",
                    memo: "#{contacts.memo}",
                    orgi: "#{inviteData.orgi}",
                    appid: "#{appid}"
                });
            }
        })
        socket.on("agentstatus", function (data) {
            document.getElementById('connect-message').innerHTML = data.message;
        })
        socket.on("status", function (data) {
            if (#{!!welcomeAd})
                output('<span id="connect-message">' + data.message + '</span>', 'message connect-message', false);
            else
                output('<span id="connect-message">' + data.message + '</span>', 'message connect-message', true);

            if (data.messageType == "end") {
                service_end = true;
                editor.readonly();
                // 因为满意度问卷在访客切换机器人坐席时也会弹出，但是服务并未结束，目前先去掉END事件时弹出满意度
                // TODO 优化方案见 https://gitlab.chatopera.com/chatopera/cosinee/issues/744
                // <#if sessionConfig?? && sessionConfig.satisfaction?? && sessionConfig.satisfaction>
                // document.getElementById("diaShade").style.display = "block";
                // document.getElementById("dialogWrap").style.display = "block";
                // isAgentEnds = true;
                // </#if>
            }

            if (document.getElementById("agentserviceid")) {
                document.getElementById("agentserviceid").value = data.agentserviceid;
            }
        })

        socket.on('message', function (data) {
            var chat = document.getElementsByClassName('chatting-left').innerText;
            data.createtime = dayjs(data.createtime).format('YYYY-MM-DD HH:mm:ss');
            chat = data.message;
            if (data.msgtype == "image") {
                chat = "<a href='" + data.message + "&original=true' target='_blank'><img src='" + data.message + "' class='ukefu-media-image'/></a>";
            } else if (data.msgtype == "file") {
                chat = "<div class='ukefu-message-file'><div class='ukefu-file-icon'><img src='/im/img/file.png'></div><div class='ukefu-file-desc'><a href='" + data.message + "' target='_blank'><div>" + data.filename + "</div><div>" + (data.filesize / 1024).toFixed(3) + "Kb</div></a></div></div>";
            }
            if (data.calltype == "呼入") {
                output('<div class="chat-right"> <img class="user-img" src="/im/img/user.png" alt=""><div class="chat-message"><label class="time">' + data.createtime + '</label><label  class="user">' + data.username + '</label> </div><div class="chatting-right"><i class="arrow arrow#{inviteData.consult_dialog_colo}"></i><div class="chat-content theme#{inviteData.consult_dialog_color}">' + chat + '</div></div>', "chat-block", true,data.msgtype
                )
                ;
            } else if (data.calltype == "呼出") {
                if (data.expmsg) {
                    showExtmsg(data.username, data.createtime, data.message, data.expmsg);
                } else {
                    output('<div class="chat-left"> <img class="user-img" src=#{dialog_headimg} alt=""><div class="chat-message"><label  class="user">' + data.username + '</label><label class="time">' + data.createtime + '</label> </div><div class="chatting-left"><i class="arrow"></i><div class="chat-content">' + chat + '</div></div>', "chat-block", true,data.msgtype);
                }
                R3Ajax.audioplayer('audioplane', newmessage, false); // 播放
            }
        });

        socket.on('disconnect', function () {
            output('<span id="connect-message">连接坐席失败，在线咨询服务不可用</span>', 'message connect-message');
        });

        socket.on('satisfaction', function () {
            if ('#{sessionConfig.satisfaction}') {
                document.getElementById("diaShade").style.display = "block";
                document.getElementById("dialogWrap").style.display = "block";
            }
        });



        function sendDisconnect() {
            socket.disconnect();
        }
        function sendMessage() {
            editor.sync();
            var count = editor.count("text");
            if (count > 0 && service_end == false) {
                var message = document.getElementById('message').value;
                if (message != "") {
                    socket.emit('message', {
                        appid: "#{appid}",
                        userid: "#{userid}",
                        type: "message",
                        session: "#{sessionid}",
                        orgi: "#{orgi}",
                        message: message
                    });
                }
            } else if (service_end == true) {
                alert("坐席已断开和您的对话");
            }
            editor.html('');
        }

        var message = {
            // text:data.message,
            // picture:function(){

            // }
            // file:function(){

            // }
            // lang:function(){

            // }
            // goods:function(){

            // }
            // POI:function(){

            // }

        }
        // 回车事件
        document.onkeyup = function (e) {
            if (!e) e = window.event;
            if ((e.keyCode || e.which) == 13) {
                document.getElementById('sent').click();
            }
        }
        window.onresize = function () {
            R3Helper.resize();
        };

